#include <iostream>
#include "XApplication.hpp"
#include "xstateMachine/xstate.hpp"
#include "concreateState.hpp"

void initStateMachine(stateSender *sender,xstateMachine *machine){
	std::cout<<"Init stateMachine"<<std::endl;
	xstate *state1 = new stateA;
	xstate *state2 = new stateB;
	xstate *state3 = new stateC;
	xstate* finalState =new xFinalState;
	
	machine->addstate(state1);
	machine->addstate(state2);
	machine->addstate(state3);
	machine->addstate(finalState);
	machine->setInitialState(state1);

	SIG::connect(state1,&stateA::sig_entered,[](){std::cout<<"state1 entered"<<std::endl;});
	SIG::connect(state2,&stateB::sig_entered,[](){std::cout<<"state2 entered"<<std::endl;});
	SIG::connect(state3,&stateC::sig_entered,[](){std::cout<<"state3 entered"<<std::endl;});
	SIG::connect(finalState,&xFinalState::sig_entered,[](){std::cout<<"finalState entered"<<std::endl;});
	SIG::connect(finalState,&xFinalState::sig_exited,[](){std::cout<<"finalState exited"<<std::endl;});
	SIG::connect(machine,&xstateMachine::sig_finished,[](){std::cout<<"machine finished"<<std::endl;});

	//状态切换信号
	state1->addTransition(sender,&stateSender::signals1Ts2,state2);
	state2->addTransition(sender,&stateSender::signals2Ts3,state3);
	state3->addTransition(sender,&stateSender::signals3Ts1,state1);

	//切换至结束状态信号绑定
	state1->addTransition(sender,&stateSender::signalsExit,finalState);
	state2->addTransition(sender,&stateSender::signalsExit,finalState);
	state3->addTransition(sender,&stateSender::signalsExit,finalState);

	//启动异步状态机循环
	machine->start();
}

int main(int argc,char**argv)
{	
	XApplication<int> a(argc,argv);

	stateSender *sender = new stateSender;
	xstateMachine *machine = new xstateMachine;

	a.registerCallback(1,initStateMachine,sender,machine);
	a.registerCallback(2,[sender = sender](){sender->emitsignals1Ts2();});
	a.registerCallback(3,[sender = sender](){sender->emitsignals2Ts3();});
	a.registerCallback(4,[sender = sender](){sender->emitsignals3Ts1();});

	a.registerCallback(5,[sender = sender](){sender->emitsignalExit();});
	
	a.m_content =  "//---------------------------------------\n"
                    "功能列表--list\n"
                    "1    initStateMachine\n"
                    "2    changeState s1->s2\n"
                    "3    changeState s2->s3\n"
                    "4    changeState s3->s1\n"
                    "5    changeState emitsignalExit\n"
				   "//---------------------------------------\n";
	//ctrl+z结束a.exec
    return a.exec([](std::string str)->int{return std::stoi(str);});
}